<template>
  <div class="containter">
    <!--面包屑导航区域-->
    <div class="header">
      --- 培训记录 ---
      <!-- 导出按钮 -->
      <div v-if="!isGuest" class="export">
        <el-button
          size="small"
          plain
          type="info"
          @click="showExportDialog = true"
          >批量导出</el-button
        >
      </div>
    </div>

    <!--卡片视图·-->
    <el-card class="box-card">
      <div class="info-search">
        <div class="info-search-content">
          <div class="info-search-content-select">
            <el-cascader
              v-model="queryInfo.groupId"
              placeholder="培训组别"
              size="small"
              :options="groupTypeOptions"
              :props="{
                checkStrictly: true,
                value: 'groupId',
                label: 'groupName',
                emitPath: true,
              }"
              @change="getRecordList()"
            ></el-cascader>
            <el-select
              v-model="queryInfo.teaType"
              placeholder="是否有指导老师参与"
              size="small"
              @change="getRecordList()"
            >
              <el-option
                v-for="item in teaType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-select
              v-model="queryInfo.duration"
              placeholder="培训时长"
              size="small"
              @change="getRecordList()"
            >
              <el-option
                v-for="item in durationType"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
            <el-cascader
              v-model="queryInfo.termType"
              placeholder="培训学期"
              size="small"
              :options="termTypeOptions"
              @change="getRecordList('term')"
            ></el-cascader>
            <el-date-picker
              v-model="queryInfo.timeRangeType"
              type="daterange"
              align="right"
              size="small"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="timeTypePickerOptions"
              :default-time="['00:00:00', '23:59:59']"
              value-format="timestamp"
              @change="getRecordList('date')"
            >
            </el-date-picker>
          </div>
        </div>
      </div>
      <RecordCard ref="recordCard" :isGuest="isGuest" />
    </el-card>
    <!-- 批量导出培训记录的窗口 -->
    <el-dialog
      :visible.sync="showExportDialog"
      title="批量导出培训记录"
      width="50%"
      :modal-append-to-body="false"
      v-loading="exportLoading"
    >
      <el-form
        ref="exportCondition"
        :model="exportCondition"
        label-width="80px"
      >
        <el-form-item label="导出组" prop="groupName">
          <el-cascader
            v-model="exportCondition.groupId"
            placeholder="请选择培训组别"
            size="small"
            :options="groupTypeOptions"
            :props="{
              checkStrictly: true,
              value: 'groupId',
              label: 'groupName',
              emitPath: false,
            }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="导出学期" prop="termType">
          <el-cascader
            v-model="exportCondition.termType"
            placeholder="请选择导出学期"
            size="small"
            :options="termTypeOptions"
          ></el-cascader>
        </el-form-item>

        <div class="submitForm">
          <el-button type="info" plain @click="showExportDialog = false"
            >取消</el-button
          >
          <el-button type="primary" plain @click="submitExport()"
            >导出</el-button
          >
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import RecordCard from "./recordCard.vue";
import configList from "../config";
export default {
  components: { RecordCard },
  data() {
    return {
      isGuest: true,
      // 查询培训记录的筛选条件
      queryInfo: {
        keyWord: "",
        groupId: [10000],
        teaType: "",
        timeRangeType: "",
        termType: "",
        duration: "",
        pageNum: 1, //页数
        pageSize: 10, //每页的size
        startDate: "",
        endDate: "",
      },
      totalRecord: 0,
      recordList: [],
      groupTypeOptions: [],
      termTypeOptions: [],
      // 导出按钮配置属性
      showExportDialog: false,
      exportLoading: false,
      exportCondition: {
        groupId: 10000,
        termType: "",
        startDate: "",
        endDate: "",
      },
      // 时间日期筛选器的快捷选项
      timeTypePickerOptions: {
        shortcuts: [
          {
            text: "本周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(
                start.getTime() - (end.getDate() - 2) * 24 * 60 * 60 * 1000
              );
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "上周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(
                start.getTime() - (end.getDate() + 5) * 24 * 60 * 60 * 1000
              );
              end.setTime(start.getTime() + 6 * 24 * 60 * 60 * 1000);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
    };
  },
  created() {
    this.superGroupType = configList.superGroupType;
    this.durationType = configList.durationType;
    this.teaType = configList.teaType;
    this.groupTypeOptions = configList.groupId;
    this.getGroupType();
    this.getTermType();
    this.isGuest = window.sessionStorage.getItem("isGuest") == "1";
  },
  mounted() {
    this.getRecordList();
  },
  methods: {
    /**
     * 获取学期信息表
     */
    async getTermType() {
      const res = await this.$axios.get(`${this.HOST}/record/api/term`);
      // console.log("term",res);
      if (res.data.meta.code == 200) {
        const terms = res.data.data.terms;
        console.log("获取学期信息成功！", terms);
        const termType = [];
        terms.forEach((ele) => {
          // console.log("ele", ele);
          let termItem = {
            label: ele.schoolYear,
            children: [
              {
                value: [ele.superior, ele.down],
                label: "全学年",
              },
              {
                value: [ele.superior, ele.mid],
                label: "上学年",
              },
              {
                value: [ele.mid, ele.down],
                label: "下学年",
              },
            ],
          };
          termType.push(termItem);
        });
        this.termTypeOptions = termType;
        // console.log("termtype,", this.termTypeOptions);
      }
    },
    /**
     * 获取培训记录（向下调用RecordCard的获取培训记录的请求）
     */
    getRecordList(entry) {
      // console.log("entry", entry);
      if (entry == "term") {
        this.queryInfo.startDate = this.queryInfo.termType[1][0];
        this.queryInfo.endDate = this.queryInfo.termType[1][1];
        this.queryInfo.timeRangeType = [];
      } else if (entry == "date") {
        this.queryInfo.startDate = this.queryInfo.timeRangeType[0];
        this.queryInfo.endDate = this.queryInfo.timeRangeType[1];
        this.queryInfo.termType = [];
      }
      // console.log(this.queryInfo);
      this.$refs.recordCard.updateQueryInfo(this.queryInfo);
    },
    handleChange() {
      // console.log(this.queryInfo);
    },
    /**
     * 获取IT培优组别树
     */
    async getGroupType() {
      let gid = JSON.parse(window.sessionStorage.getItem("groupId"));
      if (gid == null) {
        this.queryInfo.groupId = [10000];
      } else {
        this.queryInfo.groupId = gid;
      }
      // console.log("gid",this.queryInfo.groupId);
      if (window.sessionStorage.getItem("groupTree") != null) {
        this.groupTypeOptions = JSON.parse(
          window.sessionStorage.getItem("groupTree")
        );
        console.log("已从本地获得GroupTree！", this.groupTypeOptions);
        return;
      }
      const res = await this.$axios.get(`${this.HOST}/group/api/groupTree`);
      if (res.data.meta.code == 200) {
        let arr = [];
        arr.push(res.data.data.groupTree);
        this.groupTypeOptions = arr;
        console.log("组别获取成功！", this.groupTypeOptions);
        window.sessionStorage.setItem(
          "groupTree",
          JSON.stringify(this.groupTypeOptions)
        );
        // console.log(this.queryInfo.groupId);
      } else if (res.status != 200) {
        this.$message({
          message: "获取失败！",
          type: "error",
        });
      }
    },
    /**
     * 批量导出培训记录的请求
     */
    async submitExport() {
      if (
        this.exportCondition.termType == null ||
        this.exportCondition.termType == ""
      ) {
        this.$message({
          message: "请选择导出学期",
          type: "warning",
          showClose: true,
        });
        return;
      }
      this.exportCondition.startDate = this.exportCondition.termType[1][0];
      this.exportCondition.endDate = this.exportCondition.termType[1][1];
      console.log("导出参数", this.exportCondition);
      this.exportLoading = true;
      try {
        const res = await this.$axios.post(
          `${this.HOST}/admin/api/downloadGroupRecord`,
          this.exportCondition,
          { responseType: "blob" }
        );
        let data = res.data;
        this.showExportDialog = false;
        if (!data) {
          return;
        }
        let url = window.URL.createObjectURL(new Blob([data]));
        let a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        a.setAttribute("download", "培训记录统计表.xlsx");
        document.body.appendChild(a);
        a.click(); //执行下载
        window.URL.revokeObjectURL(a.href);
        document.body.removeChild(a);
      } finally {
        this.exportLoading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.containter {
  width: 75%;
  min-width: 1000px;
  margin: auto;

  .header {
    color: white;
    font-size: 28px;
    font-weight: bold;
    width: 100%;
    text-align: center;
    height: 50px;
    position: relative;

    .export {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
}
.info-search {
  min-width: 200px;
  .info-search-box {
    margin-top: 15px;
    .el-button {
      width: 100px;
    }
  }
}
.info-search-content-select {
  margin-top: 10px;
  display: flex;
  flex-direction: row;
  align-content: center;
  justify-content: space-between;
}
.info {
  .info-ul {
    height: 330px;
    .info-ul-li {
      list-style: none;
      display: inline-block;
      margin: 5px auto;
      min-width: 1050px;
    }
    .info-ul-li:hover {
      cursor: pointer;
    }
  }
}

.el-tag {
  margin-right: 5px;
}

.submitForm {
  width: 100%;
  display: flex;
  justify-content: flex-end;
}
</style>